
#include <OneButton.h>

#define EC_KEY 4
#define EC_S1 2  //data
#define EC_S2 3  //clk

OneButton SW(EC_KEY, true);

int counter = 0;
unsigned long lastInterrupt;

void click() {
  Serial.println("单击:");
}
void longclick() {
  Serial.println("长按");
}
void doubleclick() {
  Serial.println("双击");
}


void setup() {
  Serial.begin(9600);
  while (!Serial) delay(100);  // wait for native usb
  Serial.println("EC11 demo");
  // put your setup code here, to run once:
  pinMode(EC_KEY, INPUT_PULLUP);
  pinMode(EC_S1, INPUT_PULLUP);
  pinMode(EC_S2, INPUT_PULLUP);
  SW.reset();
  SW.attachClick(click);
  SW.attachDoubleClick(doubleclick);
  SW.attachLongPressStop(longclick);
  SW.setDebounceTicks(20);
  SW.setClickTicks(200);
  SW.setPressTicks(500);

  attachInterrupt(digitalPinToInterrupt(EC_S1), encoderISR, CHANGE);
}
bool state = true;
// 中断处理函数
void encoderISR() {
  Serial.print("EC_S1");
  Serial.println(digitalRead(EC_S1));
  Serial.print("EC_S2");
  Serial.println(digitalRead(EC_S2));
  if (digitalRead(EC_S1) == 0 && digitalRead(EC_S2) == 0) {
    counter++;
    Serial.println(counter);
  } else if (digitalRead(EC_S1) == 0 && digitalRead(EC_S2) == 1) {
    counter--;
    Serial.println(counter);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  SW.tick();
  delay(100);
}
